var gulpLoadPlugins =require('gulp-load-plugins');
var rollup =require("rollup").rollup;
var rollupLoadPlugins = require('rollup-load-plugins');
var fs=require('fs');

require('babel-polyfill')
require('babel-register')
var persistent = require('./persistent.js').default;

const $ = gulpLoadPlugins();
const $2 = rollupLoadPlugins();


require('events').defaultMaxListeners = 0;

function rollupPreprocess(opt) {
    return rollup({
        input: opt.entry,
        sourcemap: true,
        plugins: [
            $2.babel({
                exclude: ['**/node_modules/**', '**/babelify.js'],
                babelrc: false,
                externalHelpers: true,
                plugins:['import-directory'],
            }),
            $2.nodeBuiltins(),
            $2.includepaths({paths: ["./", __dirname + "/../"]}),
            $2.multiEntry({exports: false}),
            $2.inject({
                modules: {}
            }),
        ]
    });
}

function buildPersistentJS(opt){
    return rollup({
        input: opt.entry,
        sourcemap: true,
        plugins: [
            $2.babel({
                exclude: ['**/node_modules/**', '**/babelify.js'],
                babelrc: false,
                presets: [
                    ["es2015", {"modules": false}]
                ],
                externalHelpers: true,
                plugins:['transform-async-to-generator'],
            }),
            $2.nodeBuiltins(),
            $2.includepaths({paths: ["./", __dirname + "/../"]}),
            $2.multiEntry({exports: false}),
            $2.inject({
                modules: {
                    Promise: "server/persistent/lib/promise",
                    regeneratorRuntime: "server/persistent/lib/regeneratorRuntime",
                    Naive: "server/persistent/lib/naive"
                },
            }),
        ]
    }).then((bundle) => bundle.generate({
        format: "cjs",
    })).then((out) =>{
        let code=out.code;
        console.log(code);
        console.log("-----------------------------")
        return persistent(code);
    }).then((code)=>{
        fs.writeFileSync(opt.dest,code)
    })
}

function buildServerJS(opt){
    return rollupPreprocess(opt).then((bundle) => bundle.write({
        format: "cjs",
        dest: opt.dest,
        sourceMap: true
    }))
}

module.exports= {buildPersistentJS,buildServerJS};
